import React from 'react'
import {connect} from 'react-redux'
import BasicInfo from 'components/basic-info';
import {messages} from 'share/common';
import { Button, Input, message, Affix, Popover, Popconfirm } from 'antd';
import SlideFrame from 'components/slide-frame';
import 'styles/setting/wait-for-billing/invoice-status-query.scss';
import DataRule from 'containers/financial-account/interface-definition/data-rule';
import interfaceService from 'containers/financial-account/interface-definition/interface-service'
import Condition from 'components/condition'
import menuRoute from "routes/menuRoute";
import ResizeTable from 'components/resize-table'
const If = Condition.If;
const Search = Input.Search;

class dataDetail extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      infoList: [
        {type: 'input', id: 'detailSourceCode', label: messages('financial-account.key63')/*来源数据编码*/},
        {type: 'input', id: 'detailSourceName', label: messages('financial-account.key64')/*来源数据名称*/},
        {type: 'input', id: 'comment', label: messages('financial-account.key3')/*说明*/},
        {type: 'switch', id: 'isDefault', label: messages('financial-account.key5')/*是否预置*/},
        {type: 'switch', id: 'isEnable', label: messages('common.column.status')/*状态*/},
      ],
      infoData: {},
      columns: [
        {title: messages('financial-account.key65')/*映射字段编码*/,dataIndex: 'segmentCode', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title: messages('financial-account.key66')/*映射字段名称*/,dataIndex: 'segmentName', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title: messages('financial-account.key67')/*来源字段*/,dataIndex: 'dictCode', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title: messages('financial-account.key68')/*字段说明*/,dataIndex: 'comment', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title: messages('financial-account.key69')/*单据编号标志*/, width: 120,dataIndex: 'isBusinessCode'},
        {title: messages('financial-account.key5')/*是否预置*/,dataIndex: 'isDefault', width: 96, render: (value) => value ? messages('common.yes')/*是*/ : messages('common.no')/*否*/},
        {title: messages('common.column.status')/*状态*/,dataIndex: 'isEnable', width: 80, render: (value) => value ? messages('common.valid')/*生效*/ : messages('financial-account.key6')/*不生效*/},
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operation', width: 72, render: (value, record) => {
            let isRelative = record.childNodes && record.childNodes.length;
            return <span>
              {
                !record.isDefault && (
                  <span>
                    <a onClick={e => this.handleEdit(e, record)}>{messages('common.edit')/*编辑*/}</a>
                    <span className="ant-divider"/>
                  </span>
                )
              }
              {
                record.extendType && (
                  <Popconfirm
                    title={isRelative ? messages('financial-account.key168')/*确定要取消关联吗*/ : messages('financial-account.key169')/*确定要关联吗*/}
                    placement="topRight"
                    okText={isRelative ? messages('financial-account.key170')/*确定取消*/ : messages('financial-account.key171')/*确定关联*/}
                    onConfirm={() => this.handleSelectAddition(record)}
                  >
                    <a>{ isRelative ? messages('financial-account.key172')/*已关联*/ : messages('financial-account.key173')/*未关联*/ }</a>
                  </Popconfirm>
                )
              }
            </span>;
          }
        }
      ],
      data: [],
      loading: false,
      pagination: {
        total: 0
      },
      page: 0,
      title: '',
      editRecord: {},
      showSlideFrame: false,
      searchKey: '',
      enableAdd: false,
    }
  }

  componentDidMount() {
    this.setState({infoData: this.props.typeInterfaceDetail},() => {
      this.getList();
      this.judgeCanAdd();
    });
  }

  getList = () => {
    const { searchKey, page, infoData } = this.state;
    let temp = {
      segmentCodeOrName: searchKey,
      functionSourceGroupId: infoData.id
    };
    Object.keys(temp).map(item => {
      !temp[item] && delete temp[item];
    });
    temp.page = page;
    this.setState({loading: true});
    interfaceService.getDataList(temp).then(res => {
      this.setState({
        loading: false,
        data: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          current: page + 1,
          onChange: this.onChangePager,
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  judgeCanAdd = () => {
    const { infoData } = this.state;
    let temp = {
      functionSourceGroupId: infoData.id
    };
    interfaceService.dataCanAdd(temp).then(res => {
      this.setState({enableAdd: res.data})
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  handleChangeKey = (e) => {
    this.setState({searchKey: e.target.value, page: 0}, () => {
      this.getList();
    });
  };

  handleNew = () => {
    this.setState({
      title: messages('financial-account.key70')/*新建来源数据详情*/,
      editRecord: {}
    },() => {
      this.setState({showSlideFrame: true});
    })
  };

  handleEdit = (e,record) => {
    e.stopPropagation();
    this.setState({
      title: messages('financial-account.key71')/*编辑来源数据详情*/,
      editRecord: record
    },() => {
      this.setState({showSlideFrame: true});
    })
  };

  isRefresh = (isRefresh) => {
    this.setState({showSlideFrame: false});
    isRefresh === true && this.getList();
  };

  goBack = () => {
    this.context.router.push(menuRoute.getRouteItem('type-definition-detail').url.replace(':tab','business-type-definition'));
  };

  handleSelectAddition = record => {
    const { user } = this.props;
    let url = (record.childNodes && record.childNodes.length) ? 'cancelRelative' : 'getRelativeBasis';
    interfaceService[url]({
      functionSegmentId: record.id,
      operatorOid: user.userOID
    }).then(() => {
      this.getList();
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  render(){
    const { infoList, infoData, columns, data, loading, pagination, title, showSlideFrame, editRecord,
      enableAdd } = this.state;
    return(
      <div className="invoice-status">
        <BasicInfo infoList={infoList}
                   infoData={infoData}
                   isHideEditBtn={true}/>
        <div style={{margin:'10px 0px',height: '32px'}}>
          <If value={enableAdd}>
            <Button type="primary" onClick={this.handleNew}>{messages('common.create')}</Button>
          </If>
          <Search onChange={this.handleChangeKey}
                  style={{display:'block',float:'right',width:'400px'}}
                  placeholder={messages('financial-account.key72')/*请输入编码/名称*/}/>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey={'id'}
          pagination={pagination}
          bordered
        />
        <SlideFrame
          show={showSlideFrame}
          title={title}
          params={{
            showSlideFrame,
            editRecord
          }}
          content={DataRule}
          onClose={(isRefresh) => this.isRefresh(isRefresh)}
          afterClose={(isRefresh) => this.isRefresh(isRefresh)}
        />
        <Affix offsetBottom={0} className="bottom-bar">
          <Button onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>
        </Affix>
      </div>
    )
  }
}

dataDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    typeInterfaceDetail: state.financialAccount.typeInterfaceDetail,
    user: state.login.user
  }
}

export default connect(mapStateToProps)(dataDetail);
